package com.example.demo.modular.service;
import com.alibaba.druid.sql.visitor.functions.Trim;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.example.demo.modular.dao.GcwInfoMapper;
import com.example.demo.modular.model.GcwInfo;
import com.example.demo.util.HttpClientDownPage;
import net.sf.jsqlparser.statement.replace.Replace;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.jetty.util.StringUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
import java.io.IOException;
import java.net.URI;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Component
public class GcwService {

         @Resource
         private GcwInfoMapper gcwInfoMapper;
         @Autowired
         private BettService bettService;
//       @Resource
//       RestTemplate restTemplate;
       String sing = "";
       String groupId = IdWorker.getIdStr();
       boolean isBuy = false;
       boolean e1 = true;
       boolean start = true;
       public static Double yue2= getYuE();
       public static Double yue1= yue2;
       @Scheduled(cron = "0/1 * * * * ?")
       public String getNum(){
           while (start) {
               try {
                   String s = HttpClientDownPage.sendGet("http://www.047780.com/?shuju=1");
//           System.out.println(s);
                   if (s != null && !s.equals(sing)) {
                       String page = HttpClientDownPage.sendGet("http://www.047780.com/?id=2");
                       if (StringUtils.isNotEmpty(page)) {
                           Document parse = Jsoup.parse(page);
                           if (e1) {
                               isBuy = true;


                               Double yuE = getYuE();
                               System.out.println("已赚：" + (yuE - yue1) + "钱");
                               if (200.0 < yuE - yue2) {
                                   System.out.println("赚钱目标已达标");
                                   Thread.sleep(1000 *60*60);
                                   yue2 = getYuE();
                                   start=false;
                                   isBuy = false;
                               }
                               if (100 < yuE - yue1) {
                                   System.out.println("赚钱小目标已达标，休息会！！！！！！！！！！");
//                       yue1= getYuE();
//                       Thread.sleep(60000 * 30 );
//                       start=false;
//                       isBuy = false;
                               }
                               if (yuE - yue1 < -200.0) {
                                   System.out.println("亏了休息会！！！！！！！！！！");
//                       Thread.sleep(60000 * 30);
//                       yue1 = getYuE();
//                       isBuy = false;
                               }
                               sing = s;




                           }
                           paraseList(parse, s);



                       }
                   }

               } catch (Exception e) {
                   sing = "1111";

                   isBuy = false;
                   new Throwable(e.getMessage());
               }
           }
           return sing;
       }
    private void paraseList(Document document,String qishu) throws InterruptedException {
        //根据网页标签解析源码
        Elements elements = document.select("div[class=champion]");
        Elements elements2 = document.select("div[class=time]");
        Element element1 = elements2.get(0);
        Elements eTrs = document.select("tbody tr[class=hang]");
//        System.out.println(eTrs.size());
//        System.out.println(element1);
        String text = element1.text();
//        boolean isBuy = true;
        //去除表头
//        elements.remove(0);

            Elements elements1 = elements.get(0).select("span");
            Element message = elements1.get(0);
             String info = message.text();
            List<String> strings = Arrays.asList(info.split("\\s+"));
            System.out.println(strings);
            GcwInfo gcwInfo = new GcwInfo();
            gcwInfo.setNumber(strings.get(0)+strings.get(1));
            gcwInfo.setResult(strings.get(2));
            String substring = strings.get(4).substring(0, strings.get(4).length()-2);
            gcwInfo.setMultiple(substring);
            gcwInfo.setChance(strings.get(3));
            long s = Long.parseLong(text.split("：")[1])+1;
//            System.out.println("============="+String.valueOf(s));
            gcwInfo.setInumber(String.valueOf(s));
//            System.out.println("============="+String.valueOf(s+1));
            double v = Double.parseDouble(strings.get(3).split("：")[1].replace("%", ""));
            int money = Integer.parseInt(substring);
            String result1 = gcwInfo.getResult();
            if(isBuy&&money<=24) {
                String beeting = bettService.beeting(String.valueOf(s),result1 ,money*2);
                                System.out.println(beeting);
//                isBuy = false;
//                Thread.sleep(6000 * 10*60);

            }else if(isBuy&&24<money){
                String beeting = bettService.beeting(String.valueOf(s),result1 ,money/72*2);
//                isBuy = false;
//                Thread.sleep(6000 * 10*60);
                System.out.println(beeting);
            }
//
            boolean flag = true;
            while (flag) {
                Thread.sleep(10000);
                String result = "";
                try {
                    result = getResult();
                    e1=true;
                }catch (Exception e){
                    System.out.println("获取开奖结果异常异常！！！！！！！！！！！！！！！！！！！");
//                    isBuy = false;
//                    e1= false;
//                    result = getResult();
                }
                JSONObject jsonObject = JSON.parseObject(result);
                JSONArray data = jsonObject.getJSONArray("data");
                Map<String, String> map = (Map<String, String>) data.get(0);
                String s1 = map.get("openNumber");
                long issue = Long.parseLong(map.get("issue"));
                String[] split = s1.split(",");
                Integer s2 = Integer.parseInt(split[0])+ Integer.parseInt(split[1]) + Integer.parseInt(split[2]);
//                System.out.println(s2);
                gcwInfo.setOpenNumber(s1);
             /*   if ("小".equals(strings.get(2))) {
                    if (s2 < 11) {
                        gcwInfo.setIfOpen("中");
                        gcwInfo.setGroupId(groupId);
                        groupId=IdWorker.getIdStr();
                    } else {
                        gcwInfo.setIfOpen("挂");
                        gcwInfo.setGroupId(groupId);
                    }
                } else {
                    if (s2 < 11) {
                        gcwInfo.setIfOpen("挂");
                        gcwInfo.setGroupId(groupId);
                    } else {
                        gcwInfo.setIfOpen("中");
                        gcwInfo.setGroupId(groupId);
                        groupId=IdWorker.getIdStr();
                    }
                }*/
                if ("双".equals(strings.get(2))) {
                    if ((s2&1) !=1) {
                        gcwInfo.setIfOpen("中");
                        gcwInfo.setGroupId(groupId);
                        groupId=IdWorker.getIdStr();
                    } else {
                        gcwInfo.setIfOpen("挂");
                        gcwInfo.setGroupId(groupId);
                    }
                } else {
                    if ((s2&1) !=1) {
                        gcwInfo.setIfOpen("挂");
                        gcwInfo.setGroupId(groupId);
                    } else {
                        gcwInfo.setIfOpen("中");
                        gcwInfo.setGroupId(groupId);
                        groupId=IdWorker.getIdStr();
                    }
                }
                if(s==issue){
                    flag=false;
                }
            }
            int insert = gcwInfoMapper.insert(gcwInfo);
            System.out.println(insert);
//            QCPage qcPage = new QCPage();
//            qcPage.set(elements1.get(0).text(),elements1.get(1).text(),elements1.get(2).text(),elements1.get(3).text(),elements1.get(4).text());
//            //将解析后的实体放入集合中
//            list.add(qcPage);
//            System.out.println(result+" : " +qcPage);
//            result+=1;
        }


        /**
         * 这里解析下一页地址的标签，获取下一页的Url,然后放在redis中
         */
//        Elements elements1 = document.select("li[class=bk]").select("a");
//        for(Element element:elements1){
//            String url = element.attr("href");
//            if(StringUtil.isNotBlank(url)){
//                stringRedisTemplate.opsForList().leftPush("url",url);
//            }
//        }


    /**
     * 获取开奖结果
     */
       public String getResult() throws IOException {
           String page = HttpClientDownPage.sendGet("https://m.861656.com/v1/lottery/openResult?lotteryCode=1407&dataNum=1&");
           return page;
       }
    /**
     * 获取余额
     */
    private static Double getYuE(){
        String s1 = "";
        try {
            s1 = HttpClientDownPage.sendGetToken("https://m.861656.com/v1/balance/queryBalanceFront?");
        }catch (Exception e){
            System.out.println("获取余额异常！！！！！！！！！！！！！！");
            if(StringUtils.isEmpty(s1)){
                getYuE();
            }else {
                return Double.parseDouble(JSON.parseObject(s1).getString("data"));
            }
        }
        return Double.parseDouble(JSON.parseObject(s1).getString("data"));
    }
}
